"""Trade models for the trading platform."""

from sqlalchemy import Column, Integer, String, Text, DateTime, ForeignKey, Enum, DECIMAL, Index
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from database import Base


class Trade(Base):
    """Trade model representing a transaction between buyer and seller."""
    
    __tablename__ = 'trades'
    
    id = Column(Integer, primary_key=True, autoincrement=True)
    trade_no = Column(String(32), unique=True, nullable=False)
    product_id = Column(Integer, ForeignKey('products.id'), nullable=False)
    buyer_id = Column(Integer, ForeignKey('users.id'), nullable=False)
    seller_id = Column(Integer, ForeignKey('users.id'), nullable=False)
    amount = Column(DECIMAL(10, 2), nullable=False)
    payment_method = Column(Enum('alipay', 'wechat', 'bank_transfer', 'cash'))
    status = Column(Enum('pending_payment', 'paid', 'shipped', 'delivered', 'completed', 'cancelled', 'refunded'), 
                   default='pending_payment')
    payment_id = Column(String(64))
    remark = Column(Text)
    deadline_payment = Column(DateTime)
    deadline_delivery = Column(DateTime)
    deadline_confirm = Column(DateTime)
    completed_at = Column(DateTime)
    cancelled_at = Column(DateTime)
    created_at = Column(DateTime, default=func.now())
    updated_at = Column(DateTime, default=func.now(), onupdate=func.now())
    
    # Relationships
    product = relationship("Product")
    buyer = relationship("User", foreign_keys=[buyer_id])
    seller = relationship("User", foreign_keys=[seller_id])
    status_histories = relationship("TradeStatusHistory", back_populates="trade")
    transactions = relationship("Transaction", back_populates="trade")
    
    # Indexes
    __table_args__ = (
        Index('idx_trade_no', 'trade_no'),
        Index('idx_product_id', 'product_id'),
        Index('idx_buyer_id', 'buyer_id'),
        Index('idx_seller_id', 'seller_id'),
        Index('idx_status', 'status'),
        Index('idx_trade_created_at', 'created_at'),
    )


class TradeStatusHistory(Base):
    """Trade status history model representing status changes of a trade."""
    
    __tablename__ = 'trade_status_history'
    
    id = Column(Integer, primary_key=True, autoincrement=True)
    trade_id = Column(Integer, ForeignKey('trades.id'), nullable=False)
    from_status = Column(String(20))
    to_status = Column(String(20), nullable=False)
    operator_id = Column(Integer)
    operator_type = Column(Enum('buyer', 'seller', 'system', 'admin'))
    reason = Column(String(255))
    remark = Column(Text)
    created_at = Column(DateTime, default=func.now())
    
    # Relationships
    trade = relationship("Trade", back_populates="status_histories")
    
    # Indexes
    __table_args__ = (
        Index('idx_trade_id', 'trade_id'),
        Index('idx_trade_status_created_at', 'created_at'),
    )